package master

import (
	"context"
	"crontab/common"
	"go.etcd.io/etcd/api/v3/mvccpb"
	clientv3 "go.etcd.io/etcd/client/v3"
)

var (
	G_WorkerMgr *WorkerMgr
)

type WorkerMgr struct {
	Client *clientv3.Client
	Kv clientv3.KV
}

// 获取worker节点列表
func (w *WorkerMgr) GetWorkerList() (workerList []*common.Worker,err error) {
	var (
		key string
		getResp *clientv3.GetResponse
		kv *mvccpb.KeyValue
	)
	workerList = make([]*common.Worker,0)
	key = common.ETCD_JOB_REGISTER_DIR
	getResp,err = w.Kv.Get(context.TODO(),key,clientv3.WithPrefix())
	if err != nil {
		return
	}
	if getResp.Count == 0 {
		return
	}

	for _, kv = range getResp.Kvs {
		var (
			worker *common.Worker
		)
		// 只取IP地址
		worker = &common.Worker{}
		worker.Ip = common.GetIpAddrByKey(kv.Key)
		workerList = append(workerList,worker)
	}
	return
}

func InitWorkerMgr() {
	var (
		workerMgr *WorkerMgr
	)
	workerMgr = &WorkerMgr{
		Client: G_EtcdJob.EtcdClient,
		Kv:     G_EtcdJob.EtcdKv,
	}
	G_WorkerMgr = workerMgr
}